<template>
    <div>
        <div style="margin: 8px;">
            <el-skeleton animated :rows="8" :loading="data.isFisrt">

                <el-descriptions title="新增产品" border direction="vertical" :column="4">
                    <el-descriptions-item label="产品图片*" :span="4" align="center">
                        <el-upload :action="uploadUrl" method="post" multiple="true" list-type="picture-card"
                            :show-file-list="true" limit="4" :auto-upload="true" :on-preview="handlePictureCardPreview"
                            :on-remove="handleRemove" :on-success="event.handleSuccess" :on-error="event.handleError"
                            :file-list="file">
                            <el-icon>
                                <Plus />
                            </el-icon>
                        </el-upload>

                        <el-dialog v-model="data.dialogVisible">
                            <img w-full :src="data.dialogImageUrl" width="100%" height="100%" />
                        </el-dialog>

                    </el-descriptions-item>
                    <el-descriptions-item label="产品名称*" :span="1">
                        <el-input type="text" v-model="data.request.pname"></el-input>
                    </el-descriptions-item>
                    <el-descriptions-item label="产品价格*" :span="1">
                        <el-input-number type="text" v-model="data.request.pprice"></el-input-number>
                    </el-descriptions-item>

                    <el-descriptions-item label="产品类别*" :span="1">
                        <el-select v-model="data.request.ptid" placeholder="请选择" @change="event.children" size="large"
                            style="width: 240px">
                            <el-option v-for="item in data.ptype" :key="item.id" :label="item.name" :value="item.id" />
                        </el-select>
                    </el-descriptions-item>
                    
                    <el-descriptions-item label="产品类型*" :span="1">
                        <el-select v-model="data.request.ptype" :disabled="data.request.ptid ? false : true"
                            placeholder="请选择" size="large" style="width: 240px">
                            <el-option v-for="item in data.ptchildrenid" :key="item.id" :label="item.name"
                                :value="item.id" />
                        </el-select>
                    </el-descriptions-item>

                    <el-descriptions-item label="创建时间*" :span="1">
                        <el-date-picker type="text" v-model="data.request.pcreatetime"></el-date-picker>
                    </el-descriptions-item>
                    <el-descriptions-item label="库存*(0为不限量)" :span="1">
                        <el-input-number type="number" v-model="data.request.pCount"></el-input-number>
                    </el-descriptions-item>
                    <el-descriptions-item label="生产日期*" :span="1">
                        <el-date-picker :disabled="!data.isEdit" type="text"
                            v-model="data.request.pDate"></el-date-picker>
                    </el-descriptions-item>

                    <el-descriptions-item label="保质期(月)*" :span="1">
                        <el-input-number type="text" :disabled="!data.isEdit"
                            v-model="data.request.pshelf"></el-input-number>
                    </el-descriptions-item>
                    <el-descriptions-item label="服务时长(分钟)*" :span="1">
                        <el-input-number :disabled="data.isEdit" type="text"
                            v-model="data.request.pDuration"></el-input-number>
                    </el-descriptions-item>
                    <el-descriptions-item label="序号*" :span="1">
                        <el-input-number type="text" v-model="data.request.pno"></el-input-number>
                    </el-descriptions-item>
                    <el-descriptions-item label="产品描述*" :span="3">
                        <el-input type="text" v-model="data.request.pexplain"></el-input>
                    </el-descriptions-item>
                    <el-descriptions-item label="操作*" :span="1">
                        <el-popconfirm @confirm="event.add" title="确认要新增吗？">
                            <template #reference>
                                <el-button type="primary">新增</el-button>
                            </template>
                        </el-popconfirm>
                    </el-descriptions-item>
                </el-descriptions>

            </el-skeleton>
        </div>

    </div>
</template>

<script setup lang="ts">
import type { pro_Dto } from '@/Dto/Request/product/pro';
import { onMounted, reactive, watchEffect } from 'vue';
import { ref } from 'vue'
import { dayjs, ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import type { UploadFile, UploadFiles } from 'element-plus'
import type { UploadProps } from 'element-plus'
import { Add_Product, DeleteImg, Get_children_type, Get_Product_Type, Uploadimg } from '@/api/product';
import Api_Code from '@/Dto/Response/Api_code';
import { msg } from '@/utils/msg';
import { closeloading, startloading } from '@/utils/loading';


const data = reactive<pro_Dto>({
    isFisrt: false,
    isEdit: true,
    dialogVisible: false,
    dialogImageUrl: {},
    request: {
        pimg: [],
        pname: '',
        pprice: '',
        pcreatetime: '',
        pDate: '',
        pshelf: '',
        pCount: 0,
        ptype: '',
        pDuration: 0,
        pno: '',
        pexplain: '',
        ptid: '',
        delimg: [],
    },
    ptype: [],
    ptchildrenid: []

})

const uploadUrl = 'http://localhost:5220/api/product/UploadImage';
const file = ref<UploadFile[]>([]);
//图片放大打开模态框
const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
    data.dialogImageUrl = uploadFile.url!
    data.dialogVisible = true
}
//移除
const handleRemove: UploadProps['onRemove'] = async (uploadFile, uploadFiles) => {
    //将路径截取修改
    uploadFile.response.data.map((d: string) => [
        data.request.delimg = d.split('images/').pop()
    ])
    const delimgs = data.request.delimg;
    // 遍历数组
    data.request.pimg.forEach((item: any, index: any) => {
        if (item === delimgs) {
            // 使用 splice 删除匹配的元素
            data.request.pimg.splice(index, 1);
        }
    });
    ElMessage.error('移除成功');
}

const event = {
    //绑定子级类型
    async children() {
        data.request.ptype = ''
        data.ptchildrenid = []
        data.ptype?.forEach((d: any) => {
            if (d.id == data.request.ptid) {
                if (d.istime === 1) {
                    data.isEdit = false
                } else {
                    data.isEdit = true
                }
            }
        });
        const res = await Get_children_type({
            id: data.request.ptid,
        });
        
        if (res.code === Api_Code.ok) {
            data.ptchildrenid = res.data
        }
    },
    //上传失败的回调 
    handleError(error: Error, file: UploadFile) {
        ElMessage.error('上传失败');

    },
    //上传成功回调
    handleSuccess(response: any, file: UploadFile) {
        ElMessage.success('上传成功');

        console.log(response, ":::::::::")
        response.data.map((path: string) => {
            data.request.pimg.push(path.split('images/').pop());
        })
    },



    async add() {
        if (data.request.pimg == 0) {
            ElMessage.error('请至少上传一张照片')
            return
        }
        if (data.request.pname == "" || data.request.pprice == "" ||
            data.request.ptid == "" || data.request.ptype == "" ||
            data.request.pcreatetime == ""  || data.request.pno == "") {
            ElMessage.error('请填写完整的数据')
            return
        }
        startloading()
        const res = await Add_Product({
            ...data.request,
            pcreatetime: dayjs(data.request.pcreatetime).format('YYYY-MM-DD'),
            pData: dayjs(data.request.pDate).format('YYYY-MM-DD'),
        })
        if (res.code === Api_Code.ok) {      
            closeloading()
            msg(res)
        } else {
            msg(res)
        }
    },

}

const methods = {

    async bind() {
        const res = await Get_Product_Type()
        if (res.code === Api_Code.ok) {
            data.ptype = res.data;
        }

    },



}
onMounted(async () => {
    await methods.bind();
})

watchEffect(() => {

})

</script>

<style scoped></style>